package com.ksyun.onepass.controller;

import com.ksyun.onepass.domain.common.TradeResponse;
import com.ksyun.onepass.domain.po.BatchPayRequest;
import com.ksyun.onepass.domain.po.Response;
import com.ksyun.onepass.service.BalanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

@RequestMapping()
@RestController
@Slf4j
public class BalanceController {

    @Resource
    private CacheManager cacheManager;
    @Autowired
    private BalanceService balanceService;
    // 使用一个阻塞队列来存放请求
    private final BlockingQueue<BatchPayRequest> requestQueue = new ArrayBlockingQueue<>(100); // 限制队列大小为100

    public BalanceController(CacheManager cacheManager, BalanceService balanceService) {
        this.cacheManager = cacheManager;
        this.balanceService = balanceService;

        // 启动后台线程处理请求
        new Thread(() -> {
            while (true) {
                try {
                    // 从队列中获取请求并处理
                    BatchPayRequest request = requestQueue.take();
                    processBatchPayRequest(request);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }).start();
    }

    @PostMapping("/onePass/batchPay")
    public ResponseEntity<Response> Recharge(@RequestHeader("X-KSY-REQUEST-ID") String requestId,
                                             @RequestBody BatchPayRequest request) {

        // 判断请求ID是否已存在，确保幂等性
        if (cacheManager.getCache("BalanceCache").get(requestId) != null) {
            // 如果存在重复请求，返回响应
            Response response=new Response(200,"ok",requestId);
            return ResponseEntity.ok(response);
        }

        String batchPayId = request.getBatchPayId();
        List<Long> uids = request.getUids();

        // 将请求放入队列中
        try {
            requestQueue.put(request);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return ResponseEntity.status(500).body(new Response(500, "Internal Server Error", requestId));
        }

        //操作之后，将requestId放入缓存之中
        cacheManager.getCache("BalanceCache").put(requestId,true);

        Response response=new Response(200,"ok",requestId);
        return ResponseEntity.ok(response);
    }
    private void processBatchPayRequest(BatchPayRequest request) {
        // 处理充值逻辑
        String batchPayId = request.getBatchPayId();
        List<Long> uids = request.getUids();

        // 发起充值
        balanceService.batchPay(uids, batchPayId);

        /*
        * 可以后续补上关于mysql的数据
        * */
    }
}
